package com.rdc.example.service.impl;

import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.ColumnDTO;
import com.rdc.example.dao.ColumnDao;
import com.rdc.example.dao.impl.ColumnDaoImpl;
import com.rdc.example.dao.impl.UserDaoImpl;
import com.rdc.example.entity.Column;
import com.rdc.example.entity.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author duck
 */
public class ColumnServiceImpl implements com.rdc.example.service.ColumnService {
//    public static void main(String[] args) {
//        //List<ColumnDTO> listColumnByUserId(Integer userId)
//        ColumnServiceImpl columnService = new ColumnServiceImpl();
//        ColumnDTO dto = new ColumnDTO();
//        dto.setId(3);
//        dto.setName("路人乙栏目3");
//        //ColumnDTO.setUserId(2);
//        //Result result = columnService.updateColumn(dto);
//        List<ColumnDTO> columnDTOList = columnService.listColumnByUserId(2 );
//        System.out.println(columnDTOList);
//
//    }

    /**
     *
     * @param columnDTO
     * @return
     */
    @Override
    public Result insertColumn(ColumnDTO columnDTO) {
        try{
            ColumnDao columnDao = new ColumnDaoImpl();
            Column columnEntity = convertToEntity(columnDTO);

            boolean register = columnDao.insert(columnEntity);
            return register  ? Result.success("创建成功", null)
                    : Result.fail("创建失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param columnId
     * @return
     */
    @Override
    public Result deleteColumn(Integer columnId) {
        try{
            ColumnDao columnDao = new ColumnDaoImpl();
            boolean register = columnDao.deleteById(columnId);

            return register  ? Result.success("删除成功", null)
                    : Result.fail("删除失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param columnDTO
     * @return
     */
    @Override
    public Result updateColumn(ColumnDTO columnDTO) {
        try {
            ColumnDao columnDao = new ColumnDaoImpl();
            Column columnEntity = convertToEntity(columnDTO);
            boolean register = columnDao.update(columnEntity);
            return register ? Result.success("修改成功", null)
                    : Result.fail("修改失败", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param userId
     * @return
     */
    @Override
    public List<ColumnDTO> listColumnByUserId(Integer userId) {
        List<ColumnDTO> columnDTOList = new ArrayList<>();
        try {
            ColumnDao columnDao = new ColumnDaoImpl();
            List<Column> columnEntityList = columnDao.listColumnByUserId(userId);

            if (columnEntityList == null || columnEntityList.isEmpty()) {
                return columnDTOList;
            }
            UserDaoImpl userDao = new UserDaoImpl();
            User userEntity = userDao.getUserById(userId);
            if (userEntity == null) {
                System.err.println("用户不存在:userId=" + userId);
                return columnDTOList;
            }
            for (Column entity : columnEntityList) {
                ColumnDTO dto = convertToDto(entity);
                //dto.setUserTitle(userEntity.getTitle());
                columnDTOList.add(dto);
            }
            return convertAndEnrichColumn(columnEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return columnDTOList;
    }

    public List<ColumnDTO> searchColumnsByName(String keyword) throws Exception {
        try {
            ColumnDao columnDao = new ColumnDaoImpl();
            List<ColumnDTO> columnDTOList = new ArrayList<>();
            List<Column> columnList = columnDao.searchColumnsByName(keyword);
            if (columnList == null || columnList.isEmpty()) {
                return columnDTOList;
            }
            return convertAndEnrichColumn(columnList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<ColumnDTO> convertAndEnrichColumn(List<Column> columnEntityList) {
        List<ColumnDTO> dtos = new ArrayList<>();
        Set<Integer> userIds = columnEntityList.stream()
                .map(Column::getUserId)
                .collect(Collectors.toSet());
        UserDaoImpl userDao = new UserDaoImpl();
        Map<Integer, User> userMap = userDao.getUsersByIds(userIds);
        // 转换并填充作者信息
        for (Column entity : columnEntityList) {
            ColumnDTO dto = convertToDto(entity);
            User user = userMap.get(entity.getUserId());
            if (user != null) {
                dto.setUserName(user.getUserName());
            } else {
                dto.setUserName("未知");
                System.err.println("用户不存在: userId=" + entity.getUserId());
            }
            dtos.add(dto);
        }
        return dtos;
        //《论如何使用却搞不懂哈希表》
    }

    private ColumnDTO convertToDto(Column entity) {
        ColumnDTO dto = new ColumnDTO();
        dto.setId(entity.getId());
        dto.setUserId(entity.getUserId());
        dto.setName(entity.getName());
        dto.setCreatedAt(entity.getCreatedAt());
        return dto;
    }

    private Column convertToEntity(ColumnDTO dto) {
        Column entity = new Column();
        entity.setId(dto.getId());
        entity.setUserId(dto.getUserId());
        entity.setName(dto.getName());
        entity.setCreatedAt(dto.getCreatedAt());
        return entity;
    }

    private List<ColumnDTO> convertToDtoList(List<Column> columnEntityList) {
        List<ColumnDTO> dtos = new ArrayList<>();
        for (Column entity : columnEntityList) {
            ColumnDTO dto = convertToDto(entity);
            dtos.add(dto);
        }
        return dtos;
    }
}
